<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="所属单位" prop="unitId">
            <el-select v-model="queryParams.unitId" placeholder="请选择" filterable>
              <el-option
                v-for="item in unitList"
                :key="item.id"
                :label="item.unitName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="员工电话" prop="employeePhone">
            <el-input v-model="queryParams.employeePhone" placeholder="请输入员工联系电话" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="身份证" prop="employeeIdNumber">
            <el-input v-model="queryParams.employeeIdNumber" placeholder="请输入员工证件号码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['busi:employeeInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['busi:employeeInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['busi:employeeInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['busi:employeeInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">返回</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="employeeInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="主键id" align="center" prop="id" v-if="true" />-->
<!--        <el-table-column label="单位id" align="center" prop="unitId" />-->
        <el-table-column label="单位名称" align="center" prop="unitName" />
        <el-table-column label="员工姓名" align="center" prop="employeeName" />
        <el-table-column label="员工证件号码" align="center" prop="employeeIdNumber" />
        <el-table-column label="员工证件有效期" align="center" prop="employeeIdExpiry" />
        <el-table-column label="员工联系电话" align="center" prop="employeePhone" />
        <el-table-column label="员工邮箱" align="center" prop="employeeEmail" />
        <el-table-column label="员工性别" align="center" prop="employeeGender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.employeeGender"/>
          </template>
        </el-table-column>
        <el-table-column label="委托书有效期" align="center" prop="authorPeriod" />
        <el-table-column label="是否为经办人" align="center" prop="isOperator">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isOperator"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['busi:employeeInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['busi:employeeInfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改员工信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="employeeInfoFormRef" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-form-item label="所属单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择" disabled>
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="自然人查询系统截图" prop="systemScreenshot">
          <image-upload limit="1" v-model="form.systemScreenshot"/>
        </el-form-item>
        <el-form-item label="承诺书" prop="commitmentLetter">
          <image-upload limit="1" v-model="form.commitmentLetter"/>
        </el-form-item>
        <el-form-item label="员工身份证正面" prop="employeeIdFront">
          <template #label>
            员工身份证正面
            <el-button :loading="employeeIdFrontLoading" type="primary" icon="Camera" :disabled="!form.employeeIdFront"  plain @click="employeeIdFrontRecognition" v-hasPermi="['busi:unitInfo:add']">识别</el-button>
            <el-tooltip content="身份证正面上传后，点击识别可自动填充相关信息（注：识别可能有误，请仔细检查）" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <image-upload limit="1" v-model="form.employeeIdFront"/>
        </el-form-item>
        <el-form-item label="员工身份证正面" prop="employeeIdBack">
          <template #label>
            员工身份证反面
            <el-button :loading="employeeIdBackLoading" type="primary" icon="Camera" :disabled="!form.employeeIdBack"  plain @click="employeeIdBackRecognition" v-hasPermi="['busi:unitInfo:add']">识别</el-button>
            <el-tooltip content="身份证正面上传后，点击识别可自动填充相关信息（注：识别可能有误，请仔细检查）" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <image-upload limit="1" v-model="form.employeeIdBack"/>
        </el-form-item>
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="form.employeeName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="员工身份证地址" prop="employeeIdAddress">
          <el-input v-model="form.employeeIdAddress" placeholder="请输入员工身份证地址" />
        </el-form-item>
        <el-form-item label="员工证件号码" prop="employeeIdNumber">
          <el-input v-model="form.employeeIdNumber" placeholder="请输入员工证件号码" />
        </el-form-item>
        <el-form-item label="员工证件有效期" prop="employeeIdExpiryArr">
          <el-date-picker
            v-model="form.employeeIdExpiryArr"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY.MM.DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="员工联系电话" prop="employeePhone">
          <el-input v-model="form.employeePhone" placeholder="请输入员工联系电话" />
        </el-form-item>
        <el-form-item label="员工邮箱" prop="employeeEmail">
          <el-input v-model="form.employeeEmail" placeholder="请输入员工邮箱" />
        </el-form-item>
        <el-form-item label="员工性别" prop="employeeGender">
          <el-select v-model="form.employeeGender" placeholder="请选择员工性别">
            <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工岗位" prop="employeePost">
          <el-input v-model="form.employeePost" placeholder="请输入岗位" />
        </el-form-item>
        <el-form-item prop="isOperator" >
          <template #label>
            是否为经办人
            <el-tooltip content="每批次经办人只有一个，选择为 '是' 则会将原来的经办人置为否，会将此人设置为经办人" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-radio-group v-model="form.isOperator">
            <el-radio
              :onchange="changeIsOperator"
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="委托书有效期" prop="authorPeriod" v-if="form.isOperator === 'Y'">
          <el-select v-model="form.authorPeriod" placeholder="请选择委托书有效期">
            <el-option
              v-for="dict in staff_validity_period"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmployeeInfo" lang="ts">
import {
  listEmployeeInfo,
  getEmployeeInfo,
  delEmployeeInfo,
  addEmployeeInfo,
  updateEmployeeInfo,
  getEmployeeIdCard
} from '@/api/busi/employeeInfo';
import { EmployeeInfoVO, EmployeeInfoQuery, EmployeeInfoForm } from '@/api/busi/employeeInfo/types';
import { queryUnitList} from "@/api/busi/unitInfo";
import {UnitInfoVO} from "@/api/busi/unitInfo/types";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_user_sex, staff_validity_period } = toRefs<any>(proxy?.useDict('sys_user_sex', 'staff_validity_period'));
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));

const employeeInfoList = ref<EmployeeInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const defaultUnitId = ref("");
const employeeIdBackLoading = ref(false);
const employeeIdFrontLoading = ref(false);
// const isOperator = ref("Y");

const queryFormRef = ref<ElFormInstance>();
const employeeInfoFormRef = ref<ElFormInstance>();
const unitList = ref<UnitInfoVO[]>([]);
const route = useRoute();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EmployeeInfoForm = {
  id: undefined,
  employeeIdBack: undefined,
  employeeIdFront: undefined,
  unitId: undefined,
  employeeName: undefined,
  employeeIdAddress: undefined,
  employeeIdNumber: undefined,
  employeeIdExpiry: undefined,
  employeePhone: undefined,
  employeeEmail: undefined,
  employeeGender: undefined,
  authorPeriod: undefined,
  isOperator: "N",
}
const data = reactive<PageData<EmployeeInfoForm, EmployeeInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    employeeName: undefined,
    employeeIdNumber: undefined,
    employeePhone: undefined,
    unitId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键id不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "单位id不能为空", trigger: "blur" }
    ],
    employeeName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    employeeIdAddress: [
      { required: true, message: "员工身份证地址不能为空", trigger: "blur" }
    ],
    employeeIdNumber: [
      { required: true, message: "员工证件号码不能为空", trigger: "blur" }, { pattern: /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/, message: "请输入正确的身份证号", trigger: "blur" }
    ],
    employeeIdExpiryArr: [
      { required: true, message: "员工证件有效期不能为空", trigger: "blur" }
    ],
    employeePhone: [
      { required: true, message: "员工联系电话不能为空", trigger: "blur" },{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    employeeEmail: [
      { required: true, message: "员工邮箱不能为空", trigger: "blur" },{
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    employeeGender: [
      { required: true, message: "员工性别不能为空", trigger: "change" }
    ],
    authorPeriod: [
      { required: true, message: "委托书有效期不能为空", trigger: "blur" }
    ],
    employeeIdFront: [
      { required: true, message: "员工身份证正面不能为空", trigger: "blur" }
    ],
    employeeIdBack: [
      { required: true, message: "员工身份证反面不能为空", trigger: "blur" }
    ],
    systemScreenshot: [
      { required: true, message: "自然人查询系统截图不能为空", trigger: "blur" }
    ],
    commitmentLetter: [
      { required: true, message: "承诺书不能为空", trigger: "blur" }
    ],
    employeePost: [
      { required: true, message: "员工岗位不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工信息列表 */
const changeIsOperator = () => {
  form.value.authorPeriod = undefined;
  // isOperator.value = form.value.isOperator === "Y"? "Y" : "N";
}

/** 查询员工信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEmployeeInfo(queryParams.value);
  employeeInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询员工信息列表 */
const getUnitStaffList = async (dictId: string) => {
  loading.value = true;
  queryParams.value.unitId = dictId;
  defaultUnitId.value = dictId;
  const res = await listEmployeeInfo(queryParams.value);
  employeeInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  employeeInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.unitId = defaultUnitId.value;
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: EmployeeInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  form.value.unitId = queryParams.value.unitId;
  dialog.visible = true;
  dialog.title = "添加员工信息";
  const units = await queryUnitList();
  unitList.value = units.data;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: EmployeeInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getEmployeeInfo(_id);
  Object.assign(form.value, res.data);
  form.value.employeeIdExpiryArr = res.data.employeeIdExpiry.split('-');
  dialog.visible = true;
  dialog.title = "修改员工信息";
  const units = await queryUnitList();
  unitList.value = units.data;
}

/** 提交按钮 */
const submitForm = () => {
  employeeInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.employeeIdExpiry = form.value.employeeIdExpiryArr.join('-')
      buttonLoading.value = true;
      if (form.value.id) {
        await updateEmployeeInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addEmployeeInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 员工身份证正面识别 */
const employeeIdFrontRecognition = async () => {
  await proxy?.$modal.confirm('识别后请检查填充内容是否有误');
  employeeIdFrontLoading.value = true;
  // 打开遮罩层
  proxy?.$modal.loading("正在识别，请稍后...");
  const res = await getEmployeeIdCard(form.value.employeeIdFront).finally(() => {employeeIdFrontLoading.value = false; proxy?.$modal.closeLoading();})
  for (let key in res.data) {
    if (res.data[key]) {
      form.value[key] = res.data[key]
    }
  }
}

/** 身份证反面识别 */
const employeeIdBackRecognition = async () => {
  await proxy?.$modal.confirm('识别后请检查填充内容是否有误');
  employeeIdBackLoading.value = true;
  // 打开遮罩层
  proxy?.$modal.loading("正在识别，请稍后...");
  const res = await getEmployeeIdCard(form.value.employeeIdBack).finally(() => {employeeIdBackLoading.value = false; proxy?.$modal.closeLoading();})
  for (let key in res.data) {
    if (res.data[key]) {
      form.value[key] = res.data[key]
    }
  }
  form.value.employeeIdExpiryArr = res.data.employeeIdExpiry.split('-');

}

/** 删除按钮操作 */
const handleDelete = async (row?: EmployeeInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除员工信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delEmployeeInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('busi/employeeInfo/export', {
    ...queryParams.value
  }, `employeeInfo_${new Date().getTime()}.xlsx`)
}
/** 返回按钮操作 */
const handleClose = () => {
  const obj = { path: "/unitInfo" };
  proxy?.$tab.closeOpenPage(obj);
}
onMounted(() => {
  const units = queryUnitList();
  units.then(res => {
    unitList.value = res.data;
  })
  getUnitStaffList(route.params && route.params.unitId as string);
});

</script>
